﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;

namespace Elementum
{
    public enum SoundLevel
    {
        Light,
        Medium,
        Severe
    }

    public class MicSound
    {
        public  Microphone _microphone;
        public byte[] _buffer;
        private SoundEffectInstance _soundInstance;
        private MemoryStream _stream;
        private int _count;
        private long _soundValue;
        private int _times;
        private SoundLevel _soundLevel;

        public delegate void TooLoudEventHandler();
        public event TooLoudEventHandler TooLoud;

        public int Count
        {
            get { return _count; }
            set { _count = value; }
        }

        public MicSound(int times)
        {
            _count = 0;
            _times = times;
            _microphone = Microphone.Default;
            _microphone.BufferReady += new EventHandler<EventArgs>(microphone_BufferReady);
            _soundLevel = SoundLevel.Light;

            _soundInstance = null;
            _stream = new MemoryStream();
            TooLoud = null;
        }

        public SoundLevel SoundLevel
        {
            set
            {
                _soundLevel = value; 
            }
        }

        void microphone_BufferReady(object sender, EventArgs e)
        {
            // Retrieve audio data
            _microphone.GetData(_buffer);

            // Store the audio data in a stream
            _stream.Write(_buffer, 0, _buffer.Length);
        }

        public void Dispose() {
            if (_microphone.State == MicrophoneState.Started)
            {
                _microphone.Stop();
            }
            //if(_soundInstance!=null)
            //_soundInstance.Dispose();
            //if (_stream != null)
            //    _stream.Dispose();
        }

        public short testvalue
        {
            get;
            set;
        }

        public void Update()
        {
            _count++;
            if (_count > _times)
            {
                _count = 0;

                if (_microphone.State == MicrophoneState.Started)
                {
                    // In RECORD mode, user clicked the 
                    // stop button to end recording
                    _microphone.Stop();

                    //Thread soundThread = new Thread(new ThreadStart(playSound));
                    //soundThread.Start();
                    
                    SoundVolume();
                }
                else
                {
                    _microphone.BufferDuration = TimeSpan.FromMilliseconds(500);
                    _buffer = new byte[_microphone.GetSampleSizeInBytes(_microphone.BufferDuration)];
                    _stream.SetLength(0);
                    _microphone.Start();
                   //stream.ToArray();
                    _soundValue = 0;
                    //a = 20 * (int)Math.Log10(microphone.SampleRate);

                    //long meanAmplitude = total / amplitude.Count;
                }
            }
            else
            {
            }
        }

        private void SoundVolume()
        {
            for (int i = 0; i < _buffer.Length; i += 2)
            {
                short value = (short)(BitConverter.ToInt16(_buffer, i));
                testvalue = value;
                if (value == -32768)
                {
                    _soundValue += 32768;
                }
                else
                {
                    _soundValue += Math.Abs(value);
                }
            }
            _soundValue = _soundValue / 100;
            int tempValue;
            switch (_soundLevel)
            {
                case SoundLevel.Light:
                    tempValue = 10000;
                    break;
                case SoundLevel.Medium:
                    tempValue = 20000;
                    break;
                case SoundLevel.Severe:
                    tempValue = 30000;
                    break;
                default:
                    tempValue = 10000;
                    break;
            }
            
            if (_soundValue > tempValue && TooLoud != null)
            {
                TooLoud.Invoke();
            }
        }

        private void playSound()
        {
            // Play audio using SoundEffectInstance so we can monitor it's State 
            // and update the UI in the dt_Tick handler when it is done playing.
            try
            {
                SoundEffect sound = new SoundEffect(_stream.ToArray(), _microphone.SampleRate, AudioChannels.Mono);

                _soundInstance = sound.CreateInstance();
                //_soundInstance.Volume = 0.5f;
                //soundIsPlaying = true;
                //soundInstance.Play();
            }
            catch { }
        }
    }
}
